package com.tnt.hpit.connectBT;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.fanfq.btchat.BluetoothChatService;
import com.fanfq.btchat.R;
import com.tnt.hpit.helper.Input;
import com.tnt.hpit.helper.MyConnectHelper;

public class MyConnectHelperAndroid implements MyConnectHelper{
	// Name of the connected device
    private String mConnectedDeviceName = null;
    // Array adapter for the conversation thread
    private ArrayAdapter<String> mConversationArrayAdapter;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
	private BluetoothAdapter mBluetoothAdapter = null;
	// Member object for the chat services
	private BluetoothChatService mChatService = null;
//	private Activity callActivity;
	
	private BitmapFont font;
	
	// Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
	
    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    
 // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    
 // Debugging
    private static final String TAG = "TNT_TG_AR/MyConnectHelperAndroid";
    private static final boolean D = true;
    
    private Activity activityTNT_TG;

    public MyConnectHelperAndroid(){
	};
	public MyConnectHelperAndroid(Activity activityTNT_TG){
		this.activityTNT_TG = activityTNT_TG;
	};
	
	private ArrayList<String> mPairedDevices;
	private ArrayList<String> mNewDevices;
	
	@Override
	public void create() {
		Gdx.app.log("TNT", "Create my connect helper android");
		Looper.prepare();
//		Toast.makeText(activityTNT_TG.getBaseContext(), "Start hehe", Toast.LENGTH_LONG).show();
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		if (mBluetoothAdapter == null) {
            Toast.makeText(null, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            return;
		}
		mPairedDevices = new ArrayList<String>();
		mNewDevices = new ArrayList<String>();
		timThietBiDaGhep();
		font = new BitmapFont();
	}
	private void timThietBiDaGhep(){
		// Get a set of currently paired devices
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
		// If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices)
            	mPairedDevices.add(device.getName() + "\n" + device.getAddress());
        }
	}
	@Override
	public void start() {
		if (!mBluetoothAdapter.isEnabled())
			mBluetoothAdapter.enable();
        ensureDiscoverable();
        scan();
        
     // Register for broadcasts when a device is discovered
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        activityTNT_TG.registerReceiver(mReceiver, filter);
	}
	
	@Override
	public void render(SpriteBatch sb){
		sb.begin();
		for ( int i = 0; i < mPairedDevices.size(); i++){
			font.draw(sb, mPairedDevices.get(i), 10, 50 + 50 * i);
			Gdx.app.log( TAG, mPairedDevices.get(i));
		}
		for ( int i = 0; i < mNewDevices.size(); i++){
			font.draw(sb, mNewDevices.get(i), 250, 20 + 50 * i);
			Gdx.app.log( TAG, mNewDevices.get(i));
		}
		sb.end();
	}
	
	private void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 100);
            activityTNT_TG.startActivity(discoverableIntent);
        }
    }
	
    private static List<HashMap<String,String>> listItem = new ArrayList<HashMap<String,String>>();
    private static HashMap<String,String> map;
    private static int[] types = new int[0];
    
    public void scan(){
    	// Get a set of currently paired devices
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
//        Log.v(TAG, String.valueOf(pairedDevices.size()));
        Gdx.app.log( TAG, String.valueOf(pairedDevices.size()));
        
     // If we're already discovering, stop it
        if (mBluetoothAdapter.isDiscovering()) {
        	mBluetoothAdapter.cancelDiscovery();
        }

        // Request discover from BluetoothAdapter
        mBluetoothAdapter.startDiscovery();
//        Log.v(TAG, "Thuc hien tim kiem thiet bi moi");
        Gdx.app.log( TAG, "Thuc hien tim kiem thiet bi moi");
        
    }
    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    mNewDevices.add(device.getName() + "\n" + device.getAddress());
                    Gdx.app.log(TAG, "New device : " + device.getName() + "\n" + device.getAddress());
                }
            // When discovery is finished, change the Activity title
            }
            Gdx.app.log(TAG, "So luong device moi : " + String.valueOf(mNewDevices.size()));
           
//            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//                setProgressBarIndeterminateVisibility(false);
//                setTitle(R.string.select_device);
//                if (mNewDevicesArrayAdapter.getCount() == 0) {
//                    String noDevices = getResources().getText(R.string.none_found).toString();
//                    mNewDevicesArrayAdapter.add(noDevices);
//                }
//            }
		}
	};
	
	// Return Intent extra
    public static String EXTRA_DEVICE_ADDRESS = "device_address";
	
	// The on-click listener for all devices in the ListViews
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            // Cancel discovery because it's costly and we're about to connect
        	mBluetoothAdapter.cancelDiscovery();

            // Get the device MAC address, which is the last 17 chars in the View
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            // Create the result Intent and include the MAC address
            Intent intent = new Intent();
            intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

            // Set result and finish this Activity
            activityTNT_TG.setResult(Activity.RESULT_OK, intent);
            activityTNT_TG.finish();
        }
    };
    
}
